use tauri_plugin_http::reqwest;
use serde::{Deserialize, Serialize};
use serde_json;

/// 彩票历史记录响应结构
#[derive(Debug, Serialize, Deserialize)]
pub struct LotteryHistoryResponse {
    pub status: i32,
    pub msg: String,
    pub result: Option<LotteryHistoryResult>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LotteryHistoryResult {
    pub list: Vec<LotteryRecord>,
    pub total: i32,
    pub start: i32,
    pub num: i32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LotteryRecord {
    pub issueno: String,
    pub opendate: String,
    pub opendatetime: Option<String>,
    pub number: String,
    pub rednumber: Option<String>,
    pub bluenumber: Option<String>,
}

/// 获取彩票历史记录的 Tauri 命令
#[tauri::command]
async fn get_lottery_history(
    app_key: String,
    lottery_id: String,
    start: i32,
    num: i32,
) -> Result<LotteryHistoryResponse, String> {
    let api_base_url = "https://api.jisuapi.com/caipiao";
    let url = format!("{}/history", api_base_url);
    
    // 构建请求参数
    let params = [
        ("appkey", app_key.as_str()),
        ("caipiaoid", lottery_id.as_str()),
        ("start", &start.to_string()),
        ("num", &num.to_string()),
    ];
    
    // 使用 tauri_plugin_http::reqwest 发送请求
    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .query(&params)
        .header("Accept", "application/json, text/plain, */*")
        .header("Content-Type", "application/json")
        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
        .send()
        .await
        .map_err(|e| format!("请求失败: {}", e))?;
    
    // 检查响应状态
    if !response.status().is_success() {
        return Err(format!("HTTP 错误: {}", response.status()));
    }
    
    // 解析 JSON 响应
    let text = response.text().await.map_err(|e| format!("读取响应失败: {}", e))?;
    let lottery_response: LotteryHistoryResponse = serde_json::from_str(&text)
        .map_err(|e| format!("解析响应失败: {}", e))?;
    
    Ok(lottery_response)
}

/// 获取最近一个月的彩票历史记录
#[tauri::command]
async fn get_recent_month_history(
    app_key: String,
    lottery_id: String,
) -> Result<Vec<LotteryRecord>, String> {
    let mut all_results = Vec::new();
    let mut start = 0;
    let batch_size = 20;
    let max_records = 60; // 大约两个月的数据
    
    while start < max_records {
        let result = get_lottery_history(
            app_key.clone(),
            lottery_id.clone(),
            start,
            batch_size,
        ).await?;
        
        if result.status != 0 {
            return Err(result.msg);
        }
        
        if let Some(result_data) = result.result {
            if result_data.list.is_empty() {
                break; // 没有更多数据
            }
            
            let list_len = result_data.list.len();
            all_results.extend(result_data.list);
            
            // 如果返回的数据少于请求的数量，说明已经到底了
            if list_len < batch_size as usize {
                break;
            }
        } else {
            break;
        }
        
        start += batch_size;
        
        // 添加延迟避免API限制
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    }
    
    // 过滤出过去一个月的数据
    let one_month_ago = chrono::Utc::now() - chrono::Duration::days(30);
    let recent_data: Vec<LotteryRecord> = all_results
        .into_iter()
        .filter(|item| {
            // 使用更安全的日期解析
            match chrono::NaiveDate::parse_from_str(&item.opendate, "%Y-%m-%d") {
                Ok(open_date) => {
                    if let Some(naive_datetime) = open_date.and_hms_opt(0, 0, 0) {
                        let open_datetime = naive_datetime.and_utc();
                        open_datetime >= one_month_ago
                    } else {
                        false
                    }
                },
                Err(_) => false
            }
        })
        .collect();
    
    Ok(recent_data)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
  // 根据构建模式设置日志级别
  let log_level = if cfg!(debug_assertions) {
    log::LevelFilter::Debug
  } else {
    log::LevelFilter::Info
  };

  let builder = tauri::Builder::default()
    .plugin(tauri_plugin_http::init())
    .plugin(
      tauri_plugin_log::Builder::default()
        .level(log_level)
        .build()
    )
    .invoke_handler(tauri::generate_handler![
        get_lottery_history,
        get_recent_month_history
    ])
    .setup(|_app| {
      // 移除重复的日志插件初始化
      Ok(())
    });

  // 使用更安全的错误处理
  match builder.run(tauri::generate_context!()) {
    Ok(_) => {},
    Err(e) => {
      eprintln!("Failed to run Tauri application: {}", e);
      std::process::exit(1);
    }
  }
}
